// src/router/index.ts
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { clone } from 'ramda'
import { useAuthStore } from '@/store'
import { setupRouterPermission } from './permission'
import { constantRoutes, Layout } from './routes'
import defaultSettings from '@/settings'

import type { App } from 'vue'

const { routerWhiteList } = defaultSettings

const modules = import.meta.glob('@/views/**/*.vue')

const router = createRouter({
	history: createWebHashHistory(),
	routes: constantRoutes,
	scrollBehavior: () => ({ left: 0, top: 0 }),
})

/**
 * 重置路由
 *
 * @description 遍历所有路由，并移除不在白名单中的路由
 */
function resetRouter() {
	// console.log('getRoutes', router.getRoutes())
	router.getRoutes().forEach((route) => {
		const { name } = route
		if (name && name !== 'layout' && !routerWhiteList.includes(name as string)) {
			router.hasRoute(name) && router.removeRoute(name)
		}
	})
}
/**
 * 设置路由
 *
 * @param app Vue应用实例
 * @returns 无返回值
 */
function setupRouter(app: App<Element>): void {
	setupRouterPermission(router)
	app.use(router)
}
/**
 * 遍历添加动态路由
 *
 * @param routes 路由记录数组
 * @returns 无返回值
 */

// console.log('modules---', modules)
const filterDynamicRoutes = (routes: RouteRecordRaw[]) => {
	const tempRouts = clone(routes)
	tempRouts.forEach((item) => {
		if (!item.name) {
			item.name = item.path
		}
		// item.name??item.name = item.path
		// if (item.component?.toString().toLowerCase() == 'layout') {
		if (item.children) {
			item.component = Layout
			filterDynamicRoutes(item.children)
		} else {
			item.component = modules['/src/views' + item.component + '.vue']
			// console.log('item---', item.component)
			// if (!item.component) return
			router.addRoute('layout', item)
		}
	})
}
/**
 * 生成动态路由
 *
 */
const generateDynamicRoutes = async () => {
	const authStore = useAuthStore()
	try {
		await authStore.getMenuList()
		if (!authStore.menuList.length) {
			ElNotification({
				title: '无权限访问',
				message: '当前账号无任何菜单权限，请联系系统管理员！',
				type: 'warning',
				duration: 3000,
			})
			authStore.$reset()
			router.replace('/login')
			return Promise.reject('No permission')
		}
		// 动态添加路由
		filterDynamicRoutes(authStore.menuList)
	} catch (error) {
		authStore.$reset()
		router.replace('/login')
		return Promise.reject(error)
	}
}

export { resetRouter, setupRouter, setupRouterPermission, constantRoutes, generateDynamicRoutes }
export default router
